/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.hauntedhouses.dao.impl;

import cz.muni.fi.hauntedhouses.dao.AuthoritiesDAO;
import cz.muni.fi.hauntedhouses.entity.Authorities;
import cz.muni.fi.hauntedhouses.entity.Users;
import cz.muni.fi.hauntedhouses.to.AuthoritiesTO;
import cz.muni.fi.hauntedhouses.util.AuthoritiesUtil;
import cz.muni.fi.hauntedhouses.util.UserUtil;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import org.springframework.stereotype.Repository;

/**
 *
 * @author honzaq
 */
@Repository
public class AuthoritiesDAOImpl implements AuthoritiesDAO {
    
    private EntityManager em;
    
    @PersistenceContext
    public void setEntityManagerFactory(EntityManager em) {
        this.em = em;
    }
    
    @Override
    public void create(AuthoritiesTO role) {
        if(role == null) {
            throw new IllegalArgumentException("Role is null");
        }
        
        Authorities role_dao = AuthoritiesUtil.TOToEntity(role);
        this.em.persist(role_dao);
        role.setId(role_dao.getId());
    }

    @Override
    public AuthoritiesTO get(Long id) {
        if(id == null || id < 1) {
            throw new IllegalArgumentException("Id cannot be less than 1");
        }
        
        Authorities role = this.em.find(Authorities.class, id);
        AuthoritiesTO role_to = AuthoritiesUtil.entityToTO(role);
        return role_to;
    }

    @Override
    public void update(AuthoritiesTO role) {
        if(role == null) {
            throw new IllegalArgumentException("House is null");
        }
        Authorities role_dao = AuthoritiesUtil.TOToEntity(role);
        this.em.merge(role_dao);
    }

    @Override
    public void delete(AuthoritiesTO role) {
        if(role == null || role.getId() == null) {
            throw new IllegalArgumentException("House or id is null");
        }
        
        Authorities role_dao = AuthoritiesUtil.TOToEntity(role);
        Authorities savedRole = this.em.getReference(Authorities.class, role_dao.getId());
        try {
        this.em.remove(savedRole);
        } catch(PersistenceException ex) {
            throw new IllegalArgumentException();
        }
    }
    
}
